package com.david.IfaceAutoTest.handle;

import com.david.IfaceAutoTest.entity.CommonResult;
import com.david.IfaceAutoTest.execption.CommonException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author David
 */
@ControllerAdvice
public class ExceptionHandle {
    /**
     * 方法参数校验返回结果优化
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return  CommonResult.failed(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 全局异常捕捉
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResult handle(Exception e) {
        if (e instanceof CommonException) {
            CommonException commonException = (CommonException) e;
            return CommonResult.failed(commonException.getCode(), commonException.getMessage());
        } else {
            return CommonResult.failed(500,e.getMessage());
        }
    }
}

